<?php
App::import('Model', 'Pendapatan');

class PendapatanBL extends Pendapatan {

    public function createPendapatan($data = array(), $dataSession = array()) {
        $ret = null;
        if (!empty($data['Payroll']['divisi_id']) && ($data['Pendapatan']['karyawan_id'])==0) {
            $divisiId = $data['Payroll']['divisi_id'];
            return $this->addByDivisi($data, $divisiId);
        } else if (!empty($data['Payroll']['divisi_id']) && ($data['Pendapatan']['karyawan_id'])!=0) {
            return $this->addByKaryawan($data);
        }
    }

    public function addByDivisi($data = array(), $divisiId = NULL) {
        $ret = null;
        $arrayKaryawanToInsert = $this->Karyawan->query('SELECT * FROM karyawan WHERE divisi_id = ' . $divisiId . ' AND id NOT IN (SELECT karyawan_id FROM pendapatan)');

        foreach ($arrayKaryawanToInsert as $karyawan) {
            //pr($karyawan['karyawan']['id']);
            $data['Pendapatan']['karyawan_id'] = $karyawan['karyawan']['id'];
            //pr($data
            $this->create();
            if ($this->save($data)) {
                $ret = true;
            } else {
                $ret = false;
            }
        }

        return $ret;
    }

    function addByKaryawan($data = array()) {
        $ret = false;

        $this->create();
        if ($this->save($data)) {
            $ret = true;
        }
        
        return $ret;
    }

    function editPendapatan($data = array(), $id = null) {
        $ret = null;
            if ($this->save($data)) {
                $ret = true;
            } else {
                $ret = false;
            }
        return $ret;
    }

    function deletePendapatan($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for pendapatan', true));
            $this->redirect(array('action' => 'index'));
        }
        if ($this->Pendapatan->delete($id)) {
            $this->Session->setFlash(__('Pendapatan deleted', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Pendapatan was not deleted', true));
        $this->redirect(array('action' => 'index'));
    }

//    public function karyawanList() {
//        return $this->Karyawan->find('list', array('conditions' => array('id not in(select karyawan_id from pendapatan)')));
//    }

//    public function divisiList() {
//        $divisiBL = new DivisiBL();
//        return $divisiBL->divisiFind('list');
//    }

    public function readDetail($id = null){
        return $this->read(null, $id);
    }

    public function pendapatanFind($type='all', $options=array()) {
        return $this->find($type,$options);
    }
    
}

?>
